package com.test.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

public class MyAuthProvider implements AuthenticationProvider {
    @Autowired
    MyDetailsService userService;
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getPrincipal().toString();
        String s = authentication.getCredentials().toString();
        //数据库获取user对象
        UserDetails userDetails = userService.loadUserByUsername(username);
        //比对
        //
        String encode = new BCryptPasswordEncoder().encode(s);
        if (new BCryptPasswordEncoder().matches(s,userDetails.getPassword())){
            //密码通过 登陆成功
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                    new UsernamePasswordAuthenticationToken(
                            username, userDetails.getPassword(), userDetails.getAuthorities());
            //jwt 签名

            return usernamePasswordAuthenticationToken;
        }else {
            throw new BadCredentialsException("用户名密码错误！");
        }

    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }
}
